package model

import "server/common"

type RestfulMeau struct {
	Model
	Father   int `gorm:"column:father;type:int;default:0" json:"father"`
	FatherID *int
	Name     string `gorm:"column:name;not null;type:varchar(100);" json:"name"`

	OwnerID int `json:"owner_id" json:"owner_id" json:"owner_id"`
	Owner   Owner

	Restfuls     []Restful     `json:"childTools"`
	RestfulMeaus []RestfulMeau `gorm:"foreignKey:FatherID" json:"childMeaus"`
}

func (tr *RestfulMeau) TableName() string {
	return "restful_meau"
}

func (tr *RestfulMeau) Create() error {
	if result := common.DB.Create(&tr); result.Error != nil {
		return result.Error
	}
	return nil
}

func (tr *RestfulMeau) List(id int) []RestfulMeau {
	var tools_list []RestfulMeau
	if err := common.DB.Model(&RestfulMeau{}).Debug().Where("father = ?", id).Preload("Restfuls").Preload("RestfulMeaus").Find(&tools_list).Error; err != nil {
		return tools_list
	}

	return tools_list
}

func (tr *RestfulMeau) QueryById(id int) {
	if err := common.DB.Model(&RestfulMeau{}).Debug().Where("id = ?", id).Preload("Restfuls").Preload("RestfulMeaus").Find(&tr).Error; err != nil {
		return
	}
	return
}

func (tr *RestfulMeau) Update() error {
	if err := common.DB.Where("name = ?", tr.Name).Updates(&tr).Error; err != nil {
		return err
	}
	return nil
}

func (tr *RestfulMeau) Delete() error {
	if err := common.DB.Where("name = ?", tr.Name).Delete(&tr).Error; err != nil {
		return err
	}
	return nil
}
